suppressPackageStartupMessages(library(tidyverse))
source("Code/helper_functions.R")
options(mc.cores = parallel::detectCores())
rstan::rstan_options(auto_write = TRUE)


full_data <- read_rds("Data/Saves/full_mortality_data_2015_2021_no_2019_second_semester_2020_first_semester.rds")

stan_data_municipality_level <- full_data %>%
  group_by(covid, Municipality_code, Municipality_idx, Municipality_label) %>%
  summarise(Population = sum(Population), NbDeath = sum(NbDeath)) %>%
  create_stan_data()

set.seed(0)

municipal_level_vb_fit <- stan_data_municipality_level %>%
  rstan::vb(
    object = rstan::stan_model("Code/Poisson_loglinear_model.stan"), data = ., iter = 10^6,
    algorithm = "meanfield"
  )

if (!dir.exists("Data/Saves")) dir.create("Data/Saves")

saveRDS(object = municipal_level_vb_fit, file = "Data/Saves/electoral_stability_municipality_level_vb_no_2020_2.rds")
